package com.example.demo.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;



/*
 * 实现文件上传和下载，辅助测试，实际使用时可选择使用第三方oss存储 
 */
@RestController
@RequestMapping("/file")
public class FileServiceController {     
    @PutMapping("/upload")
    public Void uploadFile(HttpServletRequest request) {
        try (InputStream is = request.getInputStream()) {
            /*
             * 读取request的输入流，获取文件内容
             */
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            String fileId = UUID.randomUUID().toString();


            System.err.println(baos.toString());
            /*  
             * 保存文件到本地tempfile目录下
             */
            File dest = new File("tempfile/" + fileId);
            try (OutputStream os = new FileOutputStream(dest)) {
                baos.writeTo(os);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Download file
     * 文件下载demo，downloadInfo中的url为文件下载地址，可以实现文件下载功能，或者使用第三方oss进行文件下载
     * @param fileName
     * @param response
     */
    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        File file = new File("tempfile/" + fileName);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
            try (InputStream is = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
}
